﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

using YLServerInterface.GlobalClass;
using YLServerInterface.ServerConfig;

using Util;
using System.IO;
using YLPublicService.TransferModel;
using YLServiceCLient.YLAdminClient;

namespace YLServerInterface.FunctionalClass
{
    /// <summary>
    /// 为一个WorkItem服务
    /// </summary>
    class FileManager
    {
        public string WorkItemFolder { get; private set; }
        public string YazhiProjectName { get; set; }

        private FtpServerInfo FtpServer { get; set; }
        private AdminServiceClient client;
        private string workItemsFolder;
        private YLServerConfig config;
        public FileManager()
        {
            config = YLServerConfig.GetConfig();
            workItemsFolder = config.WorkItemsFolder;
            client = AdminServiceClient.GetServiceClient();
        }
        /// <summary>
        /// 获取用户在本地的文件夹
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="workItemName"></param>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        private bool GetFolder(string userName, string workItemName, out string folderPath)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 将工作项的文件下载到本地。如果文件已存在则覆盖。并吧模板文件放入。
        /// </summary>
        /// <param name="workItem"></param>
        /// <returns></returns>
        public bool PrepareWorkItem(WorkItem2ServerUser workItem)
        {
            try
            {
                FtpServer = client.RequestFtpServerInfo();
                FTP ftp = new FTP(FtpServer.IPV4, FtpServer.ClientLoginName, FtpServer.ClientPassWord);
                //下载图片放置的文件夹
                WorkItemFolder = workItemsFolder + "\\" + workItem.FilesRelativeFolder;
                Common.makeDir(WorkItemFolder);
                //下载工作项在服务器端上的所有文件
                ftp.DownloadCurrentDir(workItem.FilesRelativeFolder, WorkItemFolder); //测试成功

                #region 将在模板文件夹下文件复制到工作项文件夹
                var templateFiledir = config.TemplateFolder + "\\" + workItem.TemplateName;
                var moveFiles = Directory.GetFiles(templateFiledir);
                foreach (var moveFile in moveFiles)
                {
                    var destFile = Common.conbindPath(WorkItemFolder, Common.getFileName(moveFile));
                    File.Copy(moveFile, destFile, true);
                }
                YazhiProjectName = Directory.GetFiles(WorkItemFolder, "*.fpp")[0];
                #endregion
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
